import Schema from 'validate' 
const formInfo = new Schema({
  idcardFrontUrl:{
    type: String,
    required: true,
    message: '请填写身份证'
  },
  idcardBackUrl:{
    type: String,
    required: true,
    message: '请填写身份证'
  },
  point:{
    type: String,
    required: true,
    message: '请填写小区名'
  },
  building:{
    type: String,
    required: true,
    message: '请填写楼栋'
  },
  room:{
    type: String,
    required: true,
    message: '请填写房间名'
  },
  name:{
    required: true,
    message: '请填写姓名'
  },
  gender:{
    required: true,
    message: '请填写性别'
  },
  mobile:{
    type: String,
    required: true,
    message: '请填写手机号'
  }
},{strip:false})
Page({
  data: {
    idcardFrontUrl: '',
    idcardBackUrl: '',
    // 楼层
    point:'',
    building:'',
    room:'',
    // 个人数据
    name:'',
    gender:1,
    mobile:'',
    id:''
  },
  chooseMedia(e){
    wx.chooseMedia({
      count:1,
      mediaType:['image'],
      success:(res) => {
        wx.uploadFile({
          filePath: res.tempFiles[0].tempFilePath,
          name: 'file',
          url: wx.http.baseURL + '/upload',
          header:{
            Authorization:`Bearer ${getApp().token}`
          },
          success:(res)=>{
            const data = JSON.parse(res.data)
            // if(e.mark.type === "idcardFrontUrl"){
            //   this.setData({idcardFrontUrl:data.data.url})
            // } else{
            //   this.setData({idcardBackUrl:data.data.url})
            // }
            this.setData({[e.mark.type]:data.data.url})
          }
        })
      }
    })
  },
  async onLoad({point,building,room,id}){
    if(id){
      wx.setNavigationBarTitle({ title: '编辑房屋信息',})
      const res = await wx.http({url:`/room/${id}`})
      this.setData({...res.data})
    } else{
      this.setData({point,building,room})
    }
  },
  
  async goList() {
    const {idcardFrontUrl,idcardBackUrl,point,building,room,name,gender,mobile} = this.data
    const data = {idcardFrontUrl,idcardBackUrl,point,building,room,name,gender,mobile}
    if(this.data.id){
      console.log('this.data.id',this.data.id);
      data.id = this.data.id
    } else {

    }
    const errors = formInfo.validate(data)
    if(errors.length){
      wx.utils.toast(errors[0].message)
      return
    }
    await wx.http({
      url:'/room',
      method:'post',
      data
    })
    wx.showToast({
      title: '上传成功',
      icon: 'success'
    })
    setTimeout(() => {
      wx.navigateTo({
        url: '/house_pkg/pages/list/index',
      })
    },1000)
    // console.log('成功');
    // wx.reLaunch({
    //   url: '/house_pkg/pages/list/index',
    // })
  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark?.type
    this.setData({ [type]: '' })
  },
})
